﻿using System;
using System.Globalization;
using System.Xml;
using System.Xml.XPath;

namespace CSP.CRM.ISVExtensions
{
  public class FetchHelper
  {
    private IXPathNavigable resultDom;
    private XPathNavigator navDom;

    public FetchHelper(string resultXml)
    {
      XmlDocument auxDom = new XmlDocument();
      auxDom.LoadXml(resultXml);
      resultDom = auxDom;
      navDom = resultDom.CreateNavigator();

    }

    public FetchHelper(IXPathNavigable resultDom)
    {
      this.resultDom = resultDom;
      navDom = resultDom.CreateNavigator();
    }

    public Guid GetGuid(string attributeName)
    {
      string xpath = String.Format(CultureInfo.InvariantCulture, "/resultset/result/{0}/text()", attributeName);
      XPathNavigator textNode = navDom.SelectSingleNode(xpath);
      if (textNode != null)
        return new Guid(textNode.Value);
      else
        return Guid.Empty;
    }

    public string GetText(string attributeName)
    {
      string xpath = String.Format(CultureInfo.InvariantCulture, "/resultset/result/{0}/text()", attributeName);
      XPathNavigator textNode = navDom.SelectSingleNode(xpath);
      if (textNode != null)
        return textNode.Value;
      else
        return null;
    }

  }

}
